<template>
  <div class="list-container">
    <div
      v-for="item in list"
      :key="item.index"
      class="list-item"
      :style="{ backgroundColor: item.background }"
    >
      {{ item.index }}
    </div>
    <div v-if="loading" class="loading">Loading...</div>
  </div>
</template>

<script setup lang="ts">

import { ref, onMounted, onBeforeUnmount } from 'vue';

// 初始化基础变量
const list = ref([{ background: 'rgb(233,32,38)', index: 0 }]);
const loading = ref(false);
let scrollListener: EventListener;

// 获取模拟数据
const getList = (num: number) => {
  loading.value = true;
  
  // 模拟延迟
  setTimeout(() => {
    const currentLength = list.value.length;
    if (currentLength >= 50) {
      loading.value = false;
      return; // 渲染超过50个停止
    }
    
    for (let i = currentLength; i < currentLength + num; i++) {
      list.value.push({ background: getRandomColor(), index: i });
    }
    
    loading.value = false;
  }, getRandomDelay());
};

const getRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
};

const getRandomDelay = () => Math.floor(Math.random() * 5000); // [0,5) 秒的延迟

// 监听滚动条事件
onMounted(() => {
  scrollListener = () => {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    const clientHeight = document.documentElement.clientHeight;
    
    if (scrollTop + clientHeight >= scrollHeight / 2) {
      getList(10);
    }
  };

  window.addEventListener('scroll', scrollListener);
});

onBeforeUnmount(() => {
  window.removeEventListener('scroll', scrollListener);
});

// 初始化时调用getList获取初始数据
onMounted(() => {
  getList(10);
});
</script>

<style scoped>
.list-container {
  width: 100%;
}

.list-item {
  width: 100%;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
}

.loading {
  text-align: center;
  margin-bottom: 20px;
}
</style>
